package com.ydj.framework.filter;

import cn.hutool.core.io.IoUtil;
import com.ydj.framework.interceptor.InterceptorContext;
import lombok.Getter;
import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author rick
 */
public class ExtHttpServletRequest extends HttpServletRequestWrapper {
	/**
	 * 保存请求的body，用于多次使用
	 */
    private byte[] body;

	/**
	 * 请求的ID号，用于打LOG时候，让Req和Res可以匹配得上
	 */
    @Getter
    @Setter
    private int requestId;

    private String requestStringWithoutUrlDecode = null;

	/**
	 * 用于贯穿拦截器到Controller的一个上下文
	 */
	@Getter
    @Setter
    private InterceptorContext interceptorContext = new InterceptorContext();

    ExtHttpServletRequest(HttpServletRequest request, int requestId) throws IOException {
        super(request);
        this.body = IoUtil.readBytes(request.getInputStream());
        this.requestId = requestId;
    }

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream is = new ByteArrayInputStream(body);

        return new ServletInputStream() {
            @Override
            public int read() {
                return is.read();
            }

            @Override
            public boolean isFinished() {
                return true;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

    public String getStreamStringWithoutUrlDecode() {
        if (requestStringWithoutUrlDecode != null) {
            return requestStringWithoutUrlDecode;
        }
        ServletRequest request = getRequest();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            requestStringWithoutUrlDecode = sb.toString();
        } catch (IOException e) {
            requestStringWithoutUrlDecode = null;
        }
        return requestStringWithoutUrlDecode;
    }

    public String getRequestString() throws IOException {
        return new String(body, StandardCharsets.UTF_8);
    }

    public String getRequestStringForLog() throws IOException {
        String body = getRequestString();
        String pattern = "\"imgBase64\":\\s*\"([^\"]+)\"";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(body);
        int length = 0;
        if (m.find()) {
            String imgBase64 = m.group(1);
            length = imgBase64.length();
        }

        pattern = "(?<=\"imgBase64\": \")[^\"]*";
        return body.replaceAll(pattern, length/1024 + "K个字节的Base64图片");
    }

    public String getToken() {
        return getHeader("Authorization");
    }

    /** 获取上传文件 */
    public MultipartFile getUploadFile(String key) {
        StandardMultipartHttpServletRequest multiPartRequest = (StandardMultipartHttpServletRequest) getRequest();
        Map<String, MultipartFile> fileMap = multiPartRequest.getFileMap();
        return fileMap.get(key);
    }

    /** 获取上传文件的流 */
    public InputStream getUploadFileStream(String key) throws IOException {
        MultipartFile file = getUploadFile(key);
        if (file == null) {
            return null;
        }
        return file.getInputStream();

    }
}